import MemoryClient from 'mem0ai';
import { NextRequest, NextResponse } from 'next/server';

// 添加类型定义，提升代码可维护性
interface AddData {
  messages: Array<{ role: "user" | "assistant" | string; content: string }>;
  userId: string;
}
interface SearchData {
  userId: string;
}
interface DeleteData {
  userId: string;
}

const client = new MemoryClient({
  apiKey: process.env.MEM0_API_KEY!, // 从 .env 读取密钥（确保 .env 已添加到 .gitignore）
});

export async function POST(request: NextRequest) {
  try {
    const { action, data } = await request.json();
    // 根据 action 分发请求
    switch (action) {
      case 'add': {
        const { messages, userId } = data as AddData;
        if ((!userId || typeof userId !== "string") || (!Array.isArray(messages) || messages.length === 0)) {
          return NextResponse.json({ success: false, error: 'add 操作缺少必填参数：userId或messages' }, { status: 400 });
        }
        const result = await client.add(messages, { user_id: userId, metadata: { originalData: messages } });
      

        return NextResponse.json({ success: true, data: result });
      }
      case 'search': {
        // 获取指定用户的所有记忆（只基于 user_id）
        const { userId } = data as SearchData;
        if (!userId || typeof userId !== "string") {
          return NextResponse.json({ success: false, error: 'search 操作缺少必填参数：userId' }, { status: 400 });
        }
        const results = await client.getAll({ user_id: userId });
        console.log(results)
        return NextResponse.json({ success: true, data: results });
      }
      case 'delete': {
        // 删除指定用户的所有记忆（一个一个删除）
        const { userId } = data as DeleteData;
        if (!userId) {
          return NextResponse.json({ success: false, error: 'delete 操作缺少必填参数：memoryIds（数组）' }, { status: 400 });
        }
        await client.deleteAll({ user_id: userId }).then(result => console.log(result)).catch(error => console.error(error));
        return NextResponse.json({
          success: true,
          message: `删除成功`
        });
      }
      default:
        return NextResponse.json({ success: false, error: '未知操作' }, { status: 400 });
    }
  } catch (error) {
    console.error('mem0 代理请求失败：', error);
    return NextResponse.json({ success: false, error: '服务器内部错误' }, { status: 500 });
  }
}